// pages/audio/audio.js
let util=require("../../utils/util.js");
let baseImgUrl = util.baseImgUrl;
let app = getApp();

let qrCodePath;
let goodsPicPath;
var imageWidth;//画布宽度
var imageHeight;
var scaleRate;//缩放比
var imageTop;
let logoUrl = util.imgUrl + "kandianlogo.png";
let morenLogo = util.imgUrl + "logo.png";//用户头像，没有时用
var ewmPic = util.erweima;//二维码图片
let access_token ;
var newsSrc = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    networkStatus: true,//网络状态 默认为true
    loadingStatus: false,//默认加载完成，true--正在加载中
    loadgif: util.imgUrl + "loading.gif",//加载gif图
    loading: util.imgUrl + "loading.png",
    none_network: util.imgUrl + "none_network.png",

    baseImgUrl: baseImgUrl,
    audioshow:false,//视屏是否显示，false--视频隐藏，截图显示  true--反之
    audio_bg: baseImgUrl +"audio_bg.png",//视频播放图片
    audio_s: baseImgUrl + "audio_s.png",//小的视频播放图片
    newsSrc: "http://ones.cakeyouxuan.com/public/white_bg.png",
    wxPic: baseImgUrl +"wxPic.png",//发送给朋友
    friendsPic: baseImgUrl +"friendsPic.png",//生成海报
    weixin_l: baseImgUrl +"weixin_l.png",
    friend_l: baseImgUrl +"friend_l.png",
    scanPic: baseImgUrl +"scan.png",//图片浏览量
    greyshow: false,//是否显示分享的图片弹出框，默认为隐藏
    menushow: false,//是否显示分享选择框.默认为隐藏
    poster: 'http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400',
    
    newsId: 0,
    newstitle: "中非合作论坛北京峰会隆重开幕 习近平出席开幕式并发表主旨讲话",
    avatar: baseImgUrl+"userlogo.png",
    authorName: "凤娃凤娃",
    up_time: "2018年9月4日",
    follow: 0,
    saveFlag: 0,
    saved: baseImgUrl +"saved.png",
    unsave:baseImgUrl+"unsave.png",
    unfollow: baseImgUrl +"unfollow.png",
    followed2: baseImgUrl +"followed2.png",
    share: baseImgUrl +"share.png",
    contents: "<p>新闻的内容</p>",
    audio_picurl:  util.imgUrl + "moren_bg.jpg",//海报默认背景图
    newslists: [],

    picurl: "",
    mineavatarUrl: "",
    visitedarr:[],

    isshare: 0,//是否是分享进入。默认0，不是
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //新闻的id
    var id;
    if (options.newid) {
      id = options.newid;
      that.setData({
        newid: options.newid
      })
    } else {
      id = 0;
    }
    console.log(app.globalData.openid);
    that.setData({
      loadingStatus: true
    })

    console.log("================audio onload")
    console.log(options);
    //可以在页面 onLoad 中去获取页面 url 中的参数( 下面 onShareAppMessage 函数中配置)
    if (options.isshare == 1) {
      console.log('是分享进入');
      this.setData({
        isshare: options.isshare
      })
    }
    wx.getNetworkType({
      success: function (res) {
        var networkType = res.networkType;
        if (networkType == "none" || networkType == "unknown") {
          that.setData({
            networkStatus: false
          })
        } else {
          that.setData({
            networkStatus: true,

          })
        }
      }, fail: function (err) {
        console.log("获取网络失败" + err);
        that.setData({
          networkStatus: false
        })
      }
    })
    //获取用户头像，存到缓存
    if (app.globalData.userInfo) {
      var mineavatarUrl = app.globalData.userInfo.avatarUrl;
      wx.downloadFile({
        url: app.globalData.userInfo.avatarUrl,
        success: function (res) {
           that.setData({
            mineavatarUrl: res.tempFilePath,
          })
          that.data.mineavatarUrl = res.tempFilePath;
          console.log("我的头像图片");
          console.log(that.data.mineavatarUrl);
        }, fail: function (fres) {
          console.log("我的头像图片存缓存失败");
        }
      })
    } else {
      that.setData({
        mineavatarUrl: morenLogo
      })
    }

    //调用接口，获取新闻信息
    wx.request({
      url: util.video_info,
      data: {
        id: id,
        openid:app.globalData.openid
      },
      // method: "POST",
      // header: {
      //   "Content-Type": "application/x-www-form-urlencoded" //post
      // },
      success: function (data) {
        console.log(data);
      //如果有值
        if (data.data.newslists) {
          var res=data.data.newslists;
          var id=res.id
          var title = res.title;
          var avatar = res.avatar;
          var up_time = res.up_time;
          var user_nickname = res.user_nickname;
          var poster = res.video;
          var follow=res.follow;
          var save=res.save;
          var dianji=res.dianji;
          var au_openid=res.openid;
          var audio_picurl=res.picurl;//视频封面图片
          
          //获取分享图片的背景图
          var picurl;
          if (res.picurl) {
            picurl = res.picurl;

            wx.downloadFile({
              url: res.picurl,
              success: function (res) {

                that.setData({
                  picurl: res.tempFilePath,
                })
                that.data.picurl = res.tempFilePath;
                picurl = res.tempFilePath;
                console.log("**************res.tempFilePath************");
                console.log(res.tempFilePath);
              }, fail: function (fres) {
                console.log("存缓存失败");
              }
            })
          } else {
            picurl = util.imgUrl + "moren_bg.jpg";

          }

          that.setData({
            loadingStatus: false,
            newstitle: title,
            avatar: avatar,
            authorName: user_nickname,
            datetime: up_time,
            follow: follow,
            saveFlag: save,
            poster: poster,
            dianji:dianji,
            au_openid:au_openid,
            audio_picurl:audio_picurl,
            
          })
         
        } else {
          //接口没有返回值，页面读取默认值
          console.log("接口没有返回值" );
          that.setData({
            loadingStatus: true
          })
        }

        if(data.data.tuijian.length>0){
          that.setData({
            tuijianlist:data.data.tuijian
          })
        }

      },
      fail: function (err) {
        console.log("err" + err);
        that.setData({
          loadingStatus: true
        })
      }

    })
    setTimeout(function(){
      that.setData({
        audioshow:true
       
      })
      var myvideo = wx.createVideoContext("myVideo", myvideo);

      myvideo.play()
    },1000)

    //访问接口调取推荐视频
   
  },
  /***********推进新闻*********** */
  newsdetail: function (e) {
    var that = this;
    var thisid = e.currentTarget.dataset.id;
    that.data.visitedarr.push(thisid);
    wx.navigateTo({
      url: '/pages/detail/detail?newid=' + e.currentTarget.dataset.id
    })

  },

  /**********推荐视屏********/
  audiodetail: function (e) {
    var that = this;
    var thisid = e.currentTarget.dataset.id;
    that.data.visitedarr.push(thisid);
    wx.navigateTo({
      url: '/pages/audio/audio?newid=' + e.currentTarget.dataset.id,
    })
  },

  //点击进入发布人页面
  publisher: function () {
    wx.navigateTo({
      url: '/pages/publisher/publisher',
    })
  },
   
   
  //添加关注
  
  guanzhu: function (e) {
    var that = this;;
   
    console.log("openid" + app.globalData.openid);
    if (app.globalData.userInfo) {
      console.log("----------已授权----------------")
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      wx.request({
        url: util.guanzhu,
        data: {
          my_openid: app.globalData.openid,
          au_openid: e.currentTarget.dataset.au_openid,

        },
        success: function (res) {
          console.log("关注成功" + res);
          //修改关注值
          that.data.follow = 1;
          // var savef=e.currentTarget.dataset.savef;
          that.setData({
            follow: 1,//0--未关注，1--已关注

          })
        },
        fail: function (err) {
          console.log("err" + err)
        }
      })
    } else {
      console.log("未授权 ")
      wx.getUserInfo({
        success: function (res) {
          console.log("请求授权并成功" + res);
          //请求关注接口
          wx.request({
            url: util.guanzhu,
            data: {
              my_openid: app.globalData.openid,
              au_openid: e.currentTarget.dataset.au_openid,

            },
            success: function (res) {
              console.log("关注成功" + res);
              //修改关注值
              that.data.follow = 1;
              // var savef=e.currentTarget.dataset.savef;
              that.setData({
                follow: 1,//0--未关注，1--已关注
              })
            },
            fail: function (err) {
              console.log("err" + err)
            }
          })
         
        }, fail: function (err) {
          console.log("请求授权失败")
        }
      })

    }


  },

  //取消关注
  quxiaoguanzhu: function (e) {
    console.log(e);
    var that = this;
    //请求后台，修改关注值
    that.data.follow = 0;
    var savef = e.currentTarget.dataset.savef;
    //请求后台
    wx.request({
      url: util.quguan,
      data: {
        my_openid: app.globalData.openid,
        au_openid: e.currentTarget.dataset.au_openid,
      },
      success: function (res) {
        console.log("访问接口成功");
        console.log(res);
      },
      fail: function (err) {
        console.log("err" + err)
      }
    })
    that.setData({
      follow: 0,//0--未关注，1--已关注
        saveFlag: savef,//0--未关注，1--已关注
    })
  },

  //收藏
  shoucang: function (e) {
    var that = this;
    //请求后台，修改收藏值
    that.data.saveFlag = 1;
    var follow = e.currentTarget.dataset.follow;
    //访问接口
    wx.request({
      url: util.shoucang,
      data: {
        my_openid: app.globalData.openid,
        newid: e.currentTarget.dataset.newid
      },
      success: function (res) {
        console.log(res);
      },
      fail: function (err) {
        console.log("err" + err);
      }
    })
    that.setData({
        follow: follow,//0--未关注，1--已关注
        saveFlag: 1,//0--未关注，1--已关注
        
    })
  },

  //取消收藏
  quxiaoshoucang: function (e) {
    var that = this;
    //请求后台，修改收藏值
    that.data.saveFlag = 0;
    var follow = e.currentTarget.dataset.follow;
    wx.request({

      //新闻明细取消收藏
      url: util.qu_shoucang,
      data: {
        my_openid: app.globalData.openid,
        newid: e.currentTarget.dataset.newid
      },
      success: function (res) {
        console.log(res);
      },
      fail: function (err) {
        console.log("err" + err);
      }
    })
    that.setData({
       follow: follow,//0--未关注，1--已关注
        saveFlag: 0,//0--未关注，1--已关注
        
    })
  },


  //分享给朋友
  shareFriend: function () {
    wx.showShareMenu({
      withShareTicket: true
    })
  },

  //关闭分享图弹框
  shutgrey: function () {
    var that = this;
    that.setData({
      greyshow: false
    })
  },

  //显示分享选择菜单
  showchosemenu: function () {
    var that = this;
    that.setData({
      menushow: true
    })
  },
  //显示分享选择菜单
  hidechosemunu: function () {
    var that = this;
    that.setData({
      menushow: false
    })
  },

  /********点击分享朋友圈 生成图片*************/
  formSubmit: function (e) {
    var that = this;
    this.setData({
      menushow: false,
      
    });
    wx.showToast({
      title: '正在生成海报...',
      icon: 'loading',
      duration: 1000
    });
    setTimeout(function () {
      wx.hideToast()
      that.createNewImg();
      that.setData({
        greyshow: true
      });
    },2000)
  },

  //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
  createNewImg: function () {
    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("#fff")
    //绘制画布
    context.fillRect(0, 0, 690, 750)
    /***********上部图片路径********************/
    var pathurl = that.data.picurl;//分享图背景图，此处为视频的封面图，后台返回值
    console.log("----------------------pathurl---------------");
    console.log(pathurl);
    
    
    //绘制上部图片
    context.drawImage(pathurl, 0, 0, 375, 420);

    
   
    //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
    var path2 = that.data.mineavatarUrl;//用户的头像图
    console.log("----------------------path2---------------");
    console.log(path2);
    var path3 = logoUrl;//同城看点logo图
    var path4 = util.erweima;//二维码图片
    var path5 = util.imgUrl + "friendsPic.png";//分享朋友圈图片
    var pathline = util.imgUrl + "shortline.png";//直线
    var nickname =app.globalData.userInfo.nickName ;//作者名
    
   
    //绘制同城看点logo
     context.drawImage(path3, 210, 150, 150, 40);
    //不知道是什么原因，手机环境能正常显示
    // context.save(); // 保存当前context的状态

    //绘制名字
    context.setFontSize(26);
    context.setFillStyle('#333333');
    context.setTextAlign('left');
    /**********文章标题********/
    var newstitle = that.data.newstitle;
    
    /**********换行**开始*******/
    var chr = newstitle.split("");//这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < 345) {
        temp += chr[a];
      }
      else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);
   
    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < 330) {
          test += rowPart[a];
        }
        else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..."//这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      context.fillText(row[b], 15, 460 + b * 40, 345);
     
    }

    context.stroke();
    //绘制直线
    context.drawImage(pathline, 15, 520, 345, 1, 82);
    context.setFillStyle('#efefef');
    context.stroke();

    //绘制左下角二维码
    context.drawImage(path4, 15, 530, 100, 120);
    context.setFillStyle('#efefef');
    context.stroke();


    //绘制右下角上侧文字
    context.setFontSize(14);
    context.setFillStyle('#333');
    context.setTextAlign('left');


    /**********用户名**开始*******/
   
    nickname = nickname.split("");//这个方法是将一个字符串分割成字符串数组
    var temp2 = "";
    var row2 = [];

    for (var a = 0; a < nickname.length; a++) {
      if (context.measureText(temp2).width < 70) {
        temp2 += nickname[a];
      }
      else {
        a--; //这里添加了a-- 是为了防止字符丢失
        row2.push(temp2);
        temp2 = "";
      }
    }
    row2.push(temp2);
    console.log("row2" + row2);
   

    //如果数组长度大于1 则截取第1个
    if (row2.length > 1) {
      var rowCut2 = row2.slice(0, 1);//第一条需要截取的字符
      console.log(rowCut2);
      var rowPart2 = rowCut2[0];
      console.log("rowPart2" + rowPart2)
      var test2 = "";
      var empty2 = [];
      for (var a = 0; a < rowPart2.length; a++) {
        if (context.measureText(test2).width < 60) {
          test2 += rowPart2[a];
        }
        else {
          break;
        }
      }
      empty2.push(test2);
      console.log(empty2);
      var group2 = empty2[0] + "..."//

      rowCut2.splice(0, 1, group2);
       context.fillText(rowCut2[0], 190, 570, 70);
    }else{
      context.fillText(row2, 190, 570, 70);
    }


    context.stroke();


    /*****************************************/
    context.setFontSize(14);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText("正在观看视频", 270, 570, 164);
    context.stroke();

    //绘制右下角下侧文字
    context.setFontSize(14);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText("识别小程序，进入", 130, 630);
    context.stroke();

    context.setFontSize(14);
    context.setFillStyle('#ff1313');
    context.setTextAlign('left');
    context.fillText("同城看点", 241, 630);
    context.stroke();

    context.setFontSize(14);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText("观看视频", 300, 630);
    context.stroke();
    
    //绘制右下角上侧logo图
    context.arc(155, 565, 25, 0, 2 * Math.PI) //画出圆
    context.strokeStyle = "#efefef";
    context.clip(); //裁剪上面的圆形
    
    context.drawImage(path2, 130, 540, 50, 50, 50, 50);
    context.setFillStyle('#efefef');
    context.stroke();

    context.draw();
    //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
    setTimeout(function () {
      wx.canvasToTempFilePath({
        x: 0,
        y: 133,
        width: 690,
        height: 750,
        destHeight: 750,
        destWidth: 690,
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath,
            canvasHidden: true
          });
          that.baocun();
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 200);
  },

  //点击保存到相册
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        console.log("图片保存成功")
        // wx.showModal({
        //   content: '图片已保存到相册，赶紧晒一下吧~',
        //   showCancel: false,
        //   confirmText: '好的',
        //   confirmColor: '#333',
        //   success: function (res) {
        //     if (res.confirm) {
        //       console.log('用户点击确定');
        //       /* 该隐藏的隐藏 */
        //       that.setData({
        //         maskHidden: false
        //       })
        //     }
        //   }, fail: function (res) {
        //     console.log(11111)
        //   }
        // })
      }
    })
  },



  
    
    // wx.getImageInfo({
    //   src: 'http://ones.cakeyouxuan.com/public/white_bg.png',//服务器返回的带参数的小程序码地址
    //   success: function (res) {
    //     //res.path是网络图片的本地地址
    //     qrCodePath = res.path;
    //   },
    //   fail: function (res) {
    //     //失败回调
    //   }
    // });
  
  onShow:function(){
    var that = this;
    var newsLen = that.data.newslists.length;
    var visitLen = that.data.visitedarr.length;
    console.log("----------index onshow--------------");
    console.log(that.data.visitedarr);

    for (var i = 0; i < newsLen; i++) {
      for (var j = 0; j < visitLen; j++) {
        if (that.data.newslists[i].id == that.data.visitedarr[j]) {
          that.data.newslists[i].visited = true;

          that.setData({
            newslists: that.data.newslists
          })
        }
      };
  }
  
},
   

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
 



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: that.data.newstitle,
      path: '/pages/audio/audio?isshare=1&&newid=' + that.data.newid,
      success: function (res) {
        // 转发成功
        console.log("================success");
        console.log(that.data.isshare);
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  /**
   * 回到首页(分享的时候)
   */
  backHome: function () {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  }
})
